using System;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Kpi;
using DevExpress.ExpressApp.Security;
using DevExpress.ExpressApp.Xpo;
using DevExpress.Persistent.Base.General;
using DevExpress.Persistent.BaseImpl;
using DevExpress.Xpo;
using DomainComponents.Common;
using DomainComponents.XCRM;

namespace XCRM.Module {
    public class Updater : DevExpress.ExpressApp.Updating.ModuleUpdater {
		public const string AdministratorUserName = "Administrator";
        public Updater(IObjectSpace os, Version currentDBVersion)
            : base(os, currentDBVersion) {
        }
        public override void UpdateDatabaseAfterUpdateSchema() {
            base.UpdateDatabaseAfterUpdateSchema();

            IPersistentRole adminRole = ObjectSpace.FindObject<IPersistentRole>(new BinaryOperator("Name", "Administrators"));
            if(adminRole == null) {
                adminRole = ObjectSpace.CreateObject<IPersistentRole>();
                adminRole.Name = "Administrators";
            }
            if(adminRole.ObjectAccessPermissions.Count == 0) {
                adminRole.AddPermission(typeof(object), ObjectAccess.AllAccess);
                adminRole.CanEditModel = true;
            }
			if(ObjectSpace.FindObject<IMyAppUser>(new BinaryOperator("UserName", AdministratorUserName)) == null) {
				IMyAppUser administrator = ObjectSpace.CreateObject<IMyAppUser>();
				administrator.FirstName = AdministratorUserName;
				administrator.LastName = AdministratorUserName;
				((IDCUser)administrator).UserName = AdministratorUserName;
				((IPersistentComplexSecurityUser)administrator).IsActive = true;
				((IPersistentComplexSecurityUser)administrator).Roles.Add(adminRole);
			}
#if EasyTest
			if(ObjectSpace.FindObject<IMyAppUser>(new BinaryOperator("UserName", "User1")) == null) {
                IMyAppUser user = ObjectSpace.CreateObject<IMyAppUser>();
                user.FirstName = "User1";
                user.LastName = "User1";
                ((IDCUser)user).UserName = "User1";
                ((IPersistentComplexSecurityUser)user).IsActive = true;
                ((IPersistentComplexSecurityUser)user).Roles.Add(adminRole);
            }
#endif
			ObjectSpace.CommitChanges();

            Session session = ((XPObjectSpace)ObjectSpace).Session;
			if(ObjectSpace.FindObject<ReportData>(new BinaryOperator("ReportName", "Leads By Lead Source")) == null) {
                ReportData report = new ReportData(session, typeof(ILead));
                System.IO.Stream resourceStream = GetType().Assembly.GetManifestResourceStream("XCRM.Module.EmbeddedReports.LeadsByLeadSourceReport.repx");
                byte[] content = new byte[resourceStream.Length];
                resourceStream.Read(content, 0, (int)resourceStream.Length);
                report.ReportName = "Leads By Lead Source";
                report.Content = content;
                ((IXtraReportData)report).DataType = typeof(ICRMLead);
                report.IsInplaceReport = true;
                ObjectSpace.CommitChanges();
            }
            if(ObjectSpace.FindObject<ReportData>(new BinaryOperator("ReportName", "Contact Details")) == null) {
                ReportData report = new ReportData(session, typeof(IContact));
                System.IO.Stream resourceStream = GetType().Assembly.GetManifestResourceStream("XCRM.Module.EmbeddedReports.Contact Details.repx");
                byte[] content = new byte[resourceStream.Length];
                resourceStream.Read(content, 0, (int)resourceStream.Length);
                report.ReportName = "Contact Details";
                report.Content = content;
                ((IXtraReportData)report).DataType = typeof(ICRMContact);
                report.IsInplaceReport = true;
                ObjectSpace.CommitChanges();
            }
            if(ObjectSpace.FindObject<ReportData>(new BinaryOperator("ReportName", "Active Invoices")) == null) {
                ReportData report = new ReportData(session, typeof(IInvoice));
                System.IO.Stream resourceStream = GetType().Assembly.GetManifestResourceStream("XCRM.Module.EmbeddedReports.Active Invoices.repx");
                byte[] content = new byte[resourceStream.Length];
                resourceStream.Read(content, 0, (int)resourceStream.Length);
                report.ReportName = "Active Invoices";
                report.Content = content;
                ((IXtraReportData)report).DataType = typeof(ICRMInvoice);
                report.IsInplaceReport = true;
                ObjectSpace.CommitChanges();
            }
            if(ObjectSpace.FindObject<ReportData>(new BinaryOperator("ReportName", "Sales History")) == null) {
                ReportData report = new ReportData(session, typeof(IOpportunity));
                System.IO.Stream resourceStream = GetType().Assembly.GetManifestResourceStream("XCRM.Module.EmbeddedReports.Sales History.repx");
                byte[] content = new byte[resourceStream.Length];
                resourceStream.Read(content, 0, (int)resourceStream.Length);
                report.ReportName = "Sales History";
                report.Content = content;
                ((IXtraReportData)report).DataType = typeof(ICRMOpportunity);
                report.IsInplaceReport = true;
                ObjectSpace.CommitChanges();
            }

            CreateKpiObjects();
        }
        private void CreateKpiObjects() {
            KpiScorecard obj2 = ObjectSpace.FindObject<KpiScorecard>(CriteriaOperator.Parse("Name='Sales'"));
            if(obj2 == null) {
                obj2 = ObjectSpace.CreateObject<KpiScorecard>();
                obj2.Name = "Sales";
                obj2.Save();
            }
            KpiDefinition obj1 = ObjectSpace.FindObject<KpiDefinition>(CriteriaOperator.Parse("Name='New Leads'"));
            if(obj1 == null) {
                obj1 = ObjectSpace.CreateObject<KpiDefinition>();
                obj1.Name = "New Leads";
                obj1.TargetObjectType = typeof(ILead);
                obj1.Criteria = "CreatedOn >= '@RangeStart' And CreatedOn <= '@RangeEnd'";
                obj1.Expression = "Count";
                obj1.Range = DateRangeRepository.FindRange("ThisMonthToDate");
                obj1.Compare = true;
                obj1.RangeToCompare = DateRangeRepository.FindRange("LastMonthToDate");
                obj1.MeasurementFrequency = TimeIntervalType.Day;
                obj1.Save();
                obj2.Indicators.Add(obj1.KpiInstance);
            }
            KpiDefinition obj11 = ObjectSpace.FindObject<KpiDefinition>(CriteriaOperator.Parse("Name='New Opportunities'"));
            if(obj11 == null) {
                obj11 = ObjectSpace.CreateObject<KpiDefinition>();
                obj11.Name = "New Opportunities";
                obj11.TargetObjectType = typeof(IOpportunity);
                obj11.Criteria = "CreatedOn >= '@RangeStart' And CreatedOn <= '@RangeEnd'";
                obj11.Expression = "Count";
                obj11.Range = DateRangeRepository.FindRange("ThisMonthToDate");
                obj11.Compare = true;
                obj11.RangeToCompare = DateRangeRepository.FindRange("LastMonthToDate");
                obj11.MeasurementFrequency = TimeIntervalType.Day;
                obj11.Save();
                obj2.Indicators.Add(obj11.KpiInstance);
            }
            KpiDefinition obj12 = ObjectSpace.FindObject<KpiDefinition>(CriteriaOperator.Parse("Name='New Quotes'"));
            if(obj12 == null) {
                obj12 = ObjectSpace.CreateObject<KpiDefinition>();
                obj12.Name = "New Quotes";
                obj12.TargetObjectType = typeof(IQuote);
                obj12.Criteria = "CreatedOn >= '@RangeStart' And CreatedOn <= '@RangeEnd'";
                obj12.Expression = "Count";
                obj12.Range = DateRangeRepository.FindRange("ThisMonthToDate");
                obj12.Compare = true;
                obj12.RangeToCompare = DateRangeRepository.FindRange("LastMonthToDate");
                obj12.MeasurementFrequency = TimeIntervalType.Day;
                obj12.Save();
                obj2.Indicators.Add(obj12.KpiInstance);
            }
            KpiDefinition obj13 = ObjectSpace.FindObject<KpiDefinition>(CriteriaOperator.Parse("Name='New Orders'"));
            if(obj13 == null) {
                obj13 = ObjectSpace.CreateObject<KpiDefinition>();
                obj13.Name = "New Orders";
                obj13.TargetObjectType = typeof(IOrder);
                obj13.Criteria = "CreatedOn >= '@RangeStart' And CreatedOn <= '@RangeEnd'";
                obj13.Expression = "Count";
                obj13.Range = DateRangeRepository.FindRange("ThisMonthToDate");
                obj13.Compare = true;
                obj13.RangeToCompare = DateRangeRepository.FindRange("LastMonthToDate");
                obj13.MeasurementFrequency = TimeIntervalType.Day;
                obj13.Save();
                obj2.Indicators.Add(obj13.KpiInstance);
            }
            KpiDefinition obj14 = ObjectSpace.FindObject<KpiDefinition>(CriteriaOperator.Parse("Name='New Invoices'"));
            if(obj14 == null) {
                obj14 = ObjectSpace.CreateObject<KpiDefinition>();
                obj14.Name = "New Invoices";
                obj14.TargetObjectType = typeof(IInvoice);
                obj14.Criteria = "CreatedOn >= '@RangeStart' And CreatedOn <= '@RangeEnd'";
                obj14.Expression = "Count";
                obj14.Range = DateRangeRepository.FindRange("ThisMonthToDate");
                obj14.Compare = true;
                obj14.RangeToCompare = DateRangeRepository.FindRange("LastMonthToDate");
                obj14.MeasurementFrequency = TimeIntervalType.Day;
                obj14.Save();
                obj2.Indicators.Add(obj14.KpiInstance);
            }
            ObjectSpace.CommitChanges();
        }
    }
}
